"use strict"

const db = require("../lib/mysql")
const { success, fail, test, render } = require("../lib/result")

const add = async function(ctx, next) {
  let query = ctx.request.body || ctx.request.query
  const dic = {
    cid: {
      name: "文章 ID",
      type: "Number",
      required: true
    }
  }

  const userId = ctx.state.userInfo._id

  const queryResult = test(query, dic)
  if (queryResult.success) {
    query = queryResult.msg
    query.uid = userId
    const renderData = render(query)

    const sql = `INSERT INTO js_collections (${renderData.key.join(
      ", "
    )}) VALUES (${renderData.val.join(", ")})`

    const res = await db.query(sql)

    return res.affectedRows === 1 ? success(null) : fail(100, "添加收藏失败")
  } else {
    return fail(23, query.msg)
  }
}

const remove = async function(ctx, next) {
  let query = ctx.request.body || ctx.request.query
  const dic = {
    cid: {
      name: "文章 ID",
      type: "Number",
      required: true
    }
  }

  const userId = ctx.state.userInfo._id

  const queryResult = test(query, dic)
  if (queryResult.success) {
    query = queryResult.msg
    const sql = `DELETE FROM js_collections WHERE cid = ${query.cid} && uid = ${userId}`
    const res = await db.query(sql)
    return res.affectedRows === 1 ? success(null) : fail(100, "删除收藏失败")
  } else {
    return fail(23, query.msg)
  }
}

const get = async function(ctx, next) {
  const cid = ctx.params.id,
    userId = ctx.state.userInfo._id
  if (cid > 0) {
    const sql = `SELECT * FROM js_collections WHERE cid = ${cid} && uid = ${userId}`
    let res = await db.query(sql)
    if (res instanceof Array && res.length > 0) {
      return success(true)
    } else {
      return success(false)
    }
  } else {
    return fail(25, "请在请求路由中携带正确的文章 ID")
  }
}

module.exports = {
  add,
  remove,
  get
}
